import * as vscode from "vscode";
import {
  showErrorMessage,
  showInformationMessage,
} from "@ap/util/vscode/message";
import { userCenterToolItems } from "@ap/command";
import { getPackageJson, updatePackageJson } from "../packageJson";
import { PackageConfig } from "src/types/config";
import { arenaErrorMsg } from "../vscode/errorMsg";

// 对用户操作进行处理的函数
export const outputAndUpdateShowBar = async () => {
  try {
    const outputAndUpdateConfig =
      await getPackageJson<PackageConfig["outputAndUpdate"]>("outputAndUpdate");
    if (!outputAndUpdateConfig) {
      showInformationMessage(arenaErrorMsg.FAILED_TO_OBTAIN_THE_LIST);
      return arenaErrorMsg.FAILED_TO_OBTAIN_THE_LIST;
    }
    let outputAndUpdateConfigLiem: vscode.QuickPickItem[] = [];
    outputAndUpdateConfig.map((item) => {
      if (typeof item === "object") {
        outputAndUpdateConfigLiem.push({
          label: item.name,
          description: item.description,
          detail: `serverEntry：${item.serverEntry} —— clintEntry：${item.clientEntry}`,
        });
      } else {
        outputAndUpdateConfigLiem.push({
          label: item,
        });
      }
    });

    const selectedOption = await vscode.window.showQuickPick(
      outputAndUpdateConfigLiem,
      {
        title: "选择当前输出和上传的文件配置",
        matchOnDescription: true,
        canPickMany: false,
      },
    );

    if (selectedOption) {
      if (!selectedOption) {
        return arenaErrorMsg.FAILED_TO_OBTAIN_THE_LIST;
      }
      const index = findKeywordInArray(
        outputAndUpdateConfig,
        selectedOption.label,
      );
      if (index !== null) {
        outputAndUpdateConfig.unshift(
          outputAndUpdateConfig.splice(index, 1)[0] as never,
        );
      }
      updatePackageJson("outputAndUpdate", outputAndUpdateConfig);
      showInformationMessage(
        `已选择当前输出和上传的文件名: ${selectedOption.label}`,
      );
      return selectedOption;
    }
  } catch (error) {
    // 处理可能的用户取消操作或其他异常
    showErrorMessage(`选择操作遇到错误: ${error}`);
    return error;
  }
};

function findKeywordInArray(arr: any[], keyword: string): number | null {
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];

    // 检查字符串
    if (typeof item === "string" && item === keyword) {
      return i;
    }

    // 检查对象
    if (typeof item === "object" && item !== null) {
      if (item.name === keyword) {
        return i;
      }
    }
  }

  return null;
}
